# generate_data.py
import pandas as pd
import numpy as np
import random


def generate_normal_transaction():
    return {
        "duration_sec": max(1, np.random.gamma(shape=2, scale=3)),
        "wait_time_ms": max(1, np.random.exponential(15)),
        "rows_affected": max(1, np.random.poisson(80)),
        "lock_count": random.choice([1, 2]),
    }


def generate_anomalous_transaction():
    return {
        "duration_sec": np.random.gamma(shape=4, scale=80),  # 300~600+
        "wait_time_ms": np.random.uniform(600, 1500),
        "rows_affected": np.random.poisson(10),
        "lock_count": np.random.randint(5, 10),
    }


def generate_dataset(n_normal=900, n_anomalous=100, output_file="data/transaction_logs.csv"):
    import os
    os.makedirs("data", exist_ok=True)

    data = []

    for _ in range(n_normal):
        tx = generate_normal_transaction()
        tx["is_anomaly"] = 0
        data.append(tx)

    for _ in range(n_anomalous):
        tx = generate_anomalous_transaction()
        tx["is_anomaly"] = 1
        data.append(tx)

    df = pd.DataFrame(data)
    df = df[(df['duration_sec'] > 0) & (df['wait_time_ms'] > 0)]
    df.to_csv(output_file, index=False)

    print(f"✅ 已生成 {len(df)} 条合成数据 → {output_file}")
    print(f"📊 正常: {n_normal}, 异常: {n_anomalous}")
    return df


if __name__ == "__main__":
    generate_dataset()